package com.enoram.training2.delegate;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.enoram.training2.domain.Message;

public class MessageOldWayDelegate extends OldWayDelegate {

	public MessageOldWayDelegate(SessionFactory sessionFactory) {
		super(sessionFactory);
	}

	public void save(Message message){
		Session session = sessionFactory.getCurrentSession();

		session.beginTransaction();
		session.save(message);
		
		session.getTransaction().commit();
		
	}
	
	public void delete(Message message){
		Session session = sessionFactory.getCurrentSession();

		session.beginTransaction();
		session.delete(message);
		
		session.getTransaction().commit();
				
	}
	
	public void update(Message message){
		Session session = sessionFactory.getCurrentSession();

		session.beginTransaction();
		session.update(message);
		
		session.getTransaction().commit();
				
	}
	
	public Message load(Class clazz, Long id){
		Session session = sessionFactory.getCurrentSession();

		session.beginTransaction();
		Message result = null;
		try {
			result = (Message)session.load(clazz,id);
			if(result !=null) Hibernate.initialize(result);
			
		} catch (ObjectNotFoundException e) {
			result = null;
			e.printStackTrace();
		}
		
		session.getTransaction().commit();
		
		return result;
	}

	public List<Message> loadAll(){
	
		Session session = sessionFactory.getCurrentSession();

		session.beginTransaction();
		List<Message> result = (List<Message>)session.createQuery("from Message").list();
		session.getTransaction().commit();
		
		return result;
	}
}
